package advanced.thread;


/**
 * 死锁:  过多的同步可能造成相互不释放资源
 * 从而相互等待, 一般发生与同步中持有多个对象的锁
 * <p>
 * <p>
 * 避免:  不要再同一个代码块中, 同时持有多个对象锁(即  锁套锁)
 */
public class L11 {
    public static void main(String[] args) {
        MakeUp m1 = new MakeUp(1, "大丫");
        MakeUp m2 = new MakeUp(0, "博智");
        m1.start();
        m2.start();

    }
}

//口红
class Lipstick {

}

//镜子
class Mirror {

}

class MakeUp extends Thread {
    static Lipstick lip = new Lipstick();
    static Mirror mirror = new Mirror();

    //选择
    int choice;
    //名字
    String name;

    public MakeUp(int choice, String name) {
        this.choice = choice;
        this.name = name;
    }

    @Override
    public void run() {
        //化妆
        make();
    }

    //相互持有对方的对象锁, 才有可能导致死锁的发生
    private void make() {
        if (choice == 0) {
            synchronized (lip) {
                //获得口红锁
                System.out.println(this.name + " 涂口红");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            synchronized (mirror) {
                System.out.println(this.name + "照镜子");
            }
        } else {
            synchronized (mirror) {//获得镜子锁
                //获得口红锁
                System.out.println(this.name + "照镜子");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            synchronized (lip) {
                System.out.println(this.name + "涂口红");
            }
        }
    }
}
